import React, { Component } from 'react'
import './checkuser.scss'
import { Table, Space, Button, Popconfirm, Modal, Form, Input, Checkbox, notification, message, Select, Tooltip, Cascader,Upload } from 'antd';
import { nanoid } from 'nanoid'



import api from '../../../api'
import getBase64 from '../../../utils/getBase64'
import icon from '../../../config/iconConfig'
import residen from '../../../api/residen.json'
import { uploadAction } from '../../../constants'
const CheckboxGroup = Checkbox.Group;

const IconFont = icon.icon()
const { Option } = Select;

export default class CheckUser extends Component {
    formRef = React.createRef()
    state = {
        previewVisible: false, // 标识是否显示大图预览Modal
        previewImage: '', // 大图的url
        fileList: [
            /*{
              uid: '-1', // 每个file都有自己唯一的id
              name: 'xxx.png', // 图片文件名
              status: 'done', // 图片状态: done-已上传, uploading: 正在上传中, removed: 已删除
              url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', // 图片地址
            },*/
        ],
        listData: [],
        isModalVisible: false,
        itemId: 0,
        roleList: [],
        //身份信息
        residences: [],
        prefixSelector: (
            <Form.Item name="prefix" noStyle>
                <Select
                    style={{
                        width: 70,
                    }}
                >
                    <Option value="86">+86</Option>
                    <Option value="87">+87</Option>
                </Select>
            </Form.Item>
        ),
        formItemLayout: {
            labelCol: {
                xs: {
                    span: 24,
                },
                sm: {
                    span: 6,
                },
            },
            wrapperCol: {
                xs: {
                    span: 24,
                },
                sm: {
                    span: 12,
                },
            },
        },
    }
    hideModle = () => {
        this.setState({ isModalVisible: false })
    }
    showModle = (id) => {
        return () => {
            this.setState({ isModalVisible: true, itemId: id })
        }

    }
    //编辑
    editRole = () => {
        const { listData, itemId, roleList,fileList } = this.state
        this.formRef.current.validateFields().then(async (values) => {
            console.log(values);
            let role_id = ""
            roleList.map(item => {
                if (item.name === values.roleselect) {
                    role_id = item.roleID
                }
            })
            let time = new Date().toLocaleString();
            values.time = time;
            values.id = itemId;
            let rolena = values.roleselect
            values = { ...values, roleselect: role_id,avatar:fileList[0]?fileList[0].url:'' }
            let res = await api.user.edituser(values, time)
            console.log(res);
            if (res.data.status === 0) {//与后端代码有关res.send()
                const newList = listData.map((item)=>{
                    if(item.id === itemId){
                        let localstr = values.residence.reduce((now,courrent)=>{return now+courrent})
                        return { ...item,...values,key: nanoid(), loaction:localstr,create_time:values.time,rolename:rolena,username:(values.nickname?values.nickname:item.username),email:(values.email?values.email:item.email),phone:(values.phone?values.phone:item.phone)}
                    } else {
                        return item
                    }
                })
                this.setState({ listData: newList, isModalVisible: false })
                notification.open({
                    message: '修改成功',
                    description:
                        '太强了',
                    onClick: () => {
                        console.log('Notification Clicked!');
                    },
                });
            } else {
                message.error(res.data.msg)
            }
        })

    }
    //删除
    deleteItem = (id) => {
        const { listData } = this.state
        return async () => {
            let res = await api.user.deluser(id)
            console.log(res);
            if (res.data.status === 0) {
                const newList = listData.filter((item) => {
                    return item.id !== id
                })
                //更新状态
                this.setState({ listData: newList })
            }
        }
    }
      /*
  获取所有已上传图片文件名的数组
   */
  getImgs  = () => {
    return this.state.fileList.map(file => file.name)
  }

  /*
  隐藏Modal
   */
  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async file => {
    console.log('handlePreview()', file)
    if (!file.url && !file.preview) {
        file.preview = await getBase64.getBase64(file.originFileObj);
      }
    // 显示指定file对应的大图
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };
  /*
  file: 当前操作的图片文件(上传/删除)
  fileList: 所有已上传图片文件对象的数组
   */
  handleChange = async ({ file, fileList }) => {
    console.log('handleChange()', file.status, fileList.length, file===fileList[fileList.length-1])

    // 一旦上传成功, 将当前上传的file的信息修正(name, url)
    if(file.status==='done') {
      const result = file.response  // {status: 0, data: {name: 'xxx.jpg', url: '图片地址'}}
      if(result.status===0) {
        message.success('上传图片成功!')
        const {name, url} = result.data
        file = fileList[fileList.length-1]
        file.name = name
        file.url = url
      } else {
        message.error('上传图片失败')
      }
    } else if (file.status==='removed') { // 删除图片
      const result = await api.user.reqDeleteImg(file.name)
      console.log(result);
      if (result.data.status===0) {
        message.success('删除图片成功!')
      } else {
        message.error('删除图片失败!')
      }
    }

    // 在操作(上传/删除)过程中更新fileList状态
    this.setState({ fileList })
  };
    async componentDidMount() {
        const { listData, residences, roleList } = this.state
        this.setState({ residences: residen.provinces.province })
        let roledata = await api.role.roledata()
        console.log(roledata);
        this.setState({ roleList: roledata.data.data })
        let userdata = await api.user.datauser()
        console.log('用户数据', userdata);
        let newList = userdata.data.data.map((item, index) => {
            let localitem = JSON.parse(item.loaction)
            let localstr = localitem.reduce((now, courrent) => { return now + courrent })
            return { key: nanoid(), ...item, loaction: localstr }
        })
        console.log(newList);
        this.setState({ listData: newList, haveData: true })
    }
    render() {
        const { Column } = Table;
        const { listData, isModalVisible, formItemLayout, residences, prefixSelector, roleList,previewVisible,previewImage,fileList } = this.state
        const uploadButton = (
            <div>
              <IconFont type="icon-zengjiatianjiajiajian" />
              <div>Upload</div>
            </div>
          );
        return (!this.state.haveData ? <p className="loading" style={{ fontSize: "30px" }}>loading</p> : (
            <div id="check-user">
                <Table className="list" dataSource={listData} pagination={{ defaultPageSize: "5" }} >
                    <Column title="id" dataIndex="id" key={nanoid()} />
                    <Column title="邮箱" dataIndex="email" key={nanoid()} onFilter={(value, record) => record.email !== "admin"} defaultFilteredValue={["admin"]} />
                    <Column title="创建时间" dataIndex="create_time" key={nanoid()} />
                    <Column title="电话" dataIndex="phone" key={nanoid()} />
                    <Column title="昵称" dataIndex="username" key={nanoid()} />
                    <Column title="所在地" dataIndex="loaction" key={nanoid()} />
                    <Column title="角色" dataIndex="rolename" key={nanoid()} />
                    <Column title="操作" dataIndex="action" key={nanoid()}
                        render={(text, record) => (
                            <Space size="middle">
                                <Button type="primary" onClick={this.showModle(record.id)}>编辑</Button>
                                <Popconfirm placement="top" title='确定删除吗？' onConfirm={this.deleteItem(record.id)} okText="Yes" cancelText="No">
                                    <Button danger >删除</Button>
                                </Popconfirm>
                            </Space>
                        )}
                    />
                </Table>
                <Modal title="编辑用户" visible={isModalVisible} onOk={this.editRole} onCancel={this.hideModle} >
                    <Form
                        {...formItemLayout}
                        name="register"
                        ref={this.formRef}
                        initialValues={{
                            residence: ['浙江省', '杭州市', '余杭区'],
                            prefix: '86',
                            roleselect: "普通用户",
                        }}
                    >
                        <Form.Item
                            name="email"
                            label="E-mail"
                            rules={[
                                {
                                    type: 'email',
                                    message: '邮箱格式不正确!',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            name="phone"
                            label="电话号码"
                            rules={[
                                {
                                    max: 11,
                                    message: '请输入正确的电话号码'
                                },
                                {
                                    pattern: /^[0-9]+$/,
                                    message: '请输入正确的电话号码'
                                }
                            ]}
                        >
                            <Input
                                addonBefore={prefixSelector}
                                style={{
                                    width: '100%',
                                }}
                            />
                        </Form.Item>
                        <Form.Item
                            name="password"
                            label="密码"
                            rules={[
                                {
                                    pattern: /^[a-zA-Z]\w{5,17}$/,
                                    message: '以字母开头，长度在6~18之间，不包含特殊字符，18之间，不包含特殊字符，可以使用下划线!',
                                },
                            ]}
                            help="以字母开头，长度在6~18之间，不包含特殊字符，可以使用下划线"
                        >
                            <Input.Password />
                        </Form.Item>

                        <Form.Item
                            name="confirm"
                            label="确认密码"
                            dependencies={['password']}
                            rules={[
                                ({ getFieldValue }) => ({
                                    validator(_, value) {
                                        if (!value || getFieldValue('password') === value) {
                                            return Promise.resolve();
                                        }

                                        return Promise.reject('两次密码不相同!');
                                    },
                                }),
                            ]}
                        >
                            <Input.Password />
                        </Form.Item>

                        <Form.Item
                            name="nickname"
                            label={
                                <span>
                                    昵称&nbsp;
                                        <Tooltip title="别的名称去称呼你?也是唯一的">
                                        <IconFont type="icon-bangzhu" />
                                    </Tooltip>
                                </span>
                            }
                            rules={[
                            ]}
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            name="residence"
                            label="所在地区"
                            rules={[
                                {
                                    type: 'array',
                                    required: true,
                                    message: '选择所在地区!',
                                },
                            ]}
                        >
                            <Cascader fieldNames={{ label: 'ssqname', value: 'ssqname' }} options={residences} />
                        </Form.Item>
                        <Form.Item
                            name="roleselect"
                            label="角色选择"
                            rules={[
                                {
                                    required: true,
                                    message: '选择角色!',
                                },
                            ]}
                        >
                            <Select>
                                {
                                    roleList.map(item => {
                                        if (item.name !== "admin") {
                                            return <Option key={item.roleID} value={item.name}>{item.name}</Option>
                                        }
                                    })
                                }
                            </Select>
                        </Form.Item>
                        <Form.Item
                        label="头像设置"
                        rules={[
                            {
                                required: true,
                                message: '设置头像!',
                            },
                        ]}
                    >
                        <Upload
                            action={uploadAction} /*上传图片的接口地址*/
                            accept='image/*'  /*只接收图片格式*/
                            name="avatar"
                            listType="picture-card"  /*卡片样式*/
                            fileList={fileList}  /*所有已上传图片文件对象的数组*/
                            onPreview={this.handlePreview}
                            onChange={this.handleChange}
                        >
                            {fileList.length >= 1? null : uploadButton}
                        </Upload>
                        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                            <img alt="example" style={{ width: '100%' }} src={previewImage} />
                        </Modal>
                    </Form.Item>
                    </Form>
                </Modal>
            </div>
        ))
    }
}
